<template>
  <div class="inout-flow-container">
    <!-- 产品信息展示区域 -->
    <div class="product-info-section">
             <div class="product-info-card">
         <div class="product-name">{{ productInfo.productName }} {{ productInfo.productNo }}</div>
         <div class="product-details">
           <span class="detail-item">
             <label>货品类型：</label>
             <span>{{ productInfo.productType }}</span>
           </span>
           <span class="detail-item">
             <label>规格型号：</label>
             <span>{{ productInfo.productModel }}</span>
           </span>
           <span class="detail-item">
             <label>单位：</label>
             <span>{{ productInfo.unitName }}</span>
           </span>
         </div>
       </div>
    </div>

    <!-- 查询条件区域 -->
    <div class="search-section">
      <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
        <el-form-item label="出入库单号" prop="inOutNo">
          <el-input 
            v-model="searchForm.inOutNo" 
            placeholder="请输入出库单号/入库单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="仓库名称" prop="inventory">
          <el-select 
            v-model="searchForm.inventory" 
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="仓库一" value="仓库一" />
            <el-option label="仓库二" value="仓库二" />
            <el-option label="仓库三" value="仓库三" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="业务类型" prop="businessType">
          <el-select 
            v-model="searchForm.businessType" 
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="采购入库" value="采购入库" />
            <el-option label="销售出库" value="销售出库" />
            <el-option label="调拨入库" value="调拨入库" />
            <el-option label="调拨出库" value="调拨出库" />
            <el-option label="进货入库" value="进货入库" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="出入库类型" prop="inOutType">
          <el-select 
            v-model="searchForm.inOutType" 
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="入库" value="入库" />
            <el-option label="出库" value="出库" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="出入库日期" prop="inOutTiem">
          <el-date-picker
            v-model="searchForm.inOutTiem"
            type="date"
            placeholder="请选择"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 150px"
          />
        </el-form-item>
        
        <el-form-item label="制单日期" prop="createTime">
          <el-date-picker
            v-model="searchForm.createTime"
            type="date"
            placeholder="请选择"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 150px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="default" @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计卡片区域 -->
    <div class="statistics-section">
      <div class="statistics-cards">
        <div class="stat-card inbound-card">
          <div class="stat-title">入库统计</div>
          <div class="stat-content">
            <div class="stat-item">
              <span class="stat-label">入库数量：</span>
              <span class="stat-value inbound-value">{{ statistics.inboundQuantity }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">入库金额：</span>
              <span class="stat-value inbound-value">¥{{ statistics.inboundAmount }}</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card outbound-card">
          <div class="stat-title">出库统计</div>
          <div class="stat-content">
            <div class="stat-item">
              <span class="stat-label">出库数量：</span>
              <span class="stat-value outbound-value">{{ statistics.outboundQuantity }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">出库金额：</span>
              <span class="stat-value outbound-value">¥{{ statistics.outboundAmount }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 表格操作区域 -->
    <div class="table-actions">
      <el-button type="primary" @click="handleExport">导出</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
      <el-button @click="AddRow">新增</el-button>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <el-table 
        :data="tableData" 
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="60" />
        <el-table-column prop="inOutNo" label="出入库单号" width="150" />
        <el-table-column prop="inOutTiem" label="出入库日期" width="120" />
        <el-table-column prop="businessType" label="业务类型" width="120" />
        <el-table-column prop="inOutType" label="出入库类型" width="100" />
        <el-table-column prop="inventory" label="仓库名称" width="100" />
        <el-table-column prop="inNumber" label="入库数量" width="100" />
        <el-table-column prop="outNumbber" label="出库数量" width="100" />
                 <el-table-column prop="inMoney" label="入库金额" width="120">
           <template #default="scope">
             {{ scope.row.inMoney ? `¥${scope.row.inMoney}` : '' }}
           </template>
         </el-table-column>
         <el-table-column prop="outMoney" label="出库金额" width="120">
           <template #default="scope">
             {{ scope.row.outMoney ? `¥${scope.row.outMoney}` : '' }}
           </template>
         </el-table-column>
        <el-table-column prop="createer" label="制单人" width="100" />
        <el-table-column prop="createTime" label="制单日期" width="120" />
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.pageIndex"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增弹窗功能 -->
    <el-dialog v-model="dialogVisible" title="新增出入库流水" width="600px" :close-on-click-modal="false" @close="handleDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出入库单号" prop="inOutNo">
              <el-input v-model="addForm.inOutNo" placeholder="请输入出入库单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出入库日期" prop="inOutTiem">
              <el-date-picker
                v-model="addForm.inOutTiem"
                type="date"
                placeholder="请选择出入库日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务类型" prop="businessType">
              <el-select v-model="addForm.businessType" placeholder="请选择业务类型" style="width: 100%">
                <el-option label="采购入库" value="采购入库" />
                <el-option label="销售出库" value="销售出库" />
                <el-option label="调拨入库" value="调拨入库" />
                <el-option label="调拨出库" value="调拨出库" />
                <el-option label="进货入库" value="进货入库" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出入库类型" prop="inOutType">
              <el-select v-model="addForm.inOutType" placeholder="请选择出入库类型" style="width: 100%">
                <el-option label="入库" value="入库" />
                <el-option label="出库" value="出库" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库数量" prop="inNumber">
              <el-input-number 
                v-model="addForm.inNumber" 
                :min="0" 
                :controls="true"
                :step="1"
                :precision="0"
                placeholder="请输入入库数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库数量" prop="outNumbber">
              <el-input-number 
                v-model="addForm.outNumbber" 
                :min="0" 
                :controls="true"
                :step="1"
                :precision="0"
                placeholder="请输入出库数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库金额" prop="inMoney">
              <el-input-number 
                v-model="addForm.inMoney" 
                :min="0" 
                :precision="2"
                :controls="true"
                :step="0.01"
                placeholder="请输入入库金额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库金额" prop="outMoney">
              <el-input-number 
                v-model="addForm.outMoney" 
                :min="0" 
                :precision="2"
                :controls="true"
                :step="0.01"
                placeholder="请输入出库金额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品" prop="productI_Id">
              <el-input v-model="addForm.productName" placeholder="商品信息" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品批次" prop="batch_Id">
              <el-input v-model="addForm.batch_Id" placeholder="商品批次将自动反显" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        

        

      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit" :loading="addLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { TZRead,TZWrite } from '@/http/interceptors'
import { useRouter,useRoute } from 'vue-router'
import moment from 'moment'
const router=useRouter();
const route=useRoute();

// 查询表单数据
const searchForm = reactive({
  inOutNo: '',
  inventory: '',
  businessType: '',
  inOutType: '',
  inOutTiem: '',
  createTime: '',
  productId: route.query.id // 从路由参数获取商品ID
})

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 商品详情数据
const productInfo = reactive({
  productName: '',
  productNo: '',
  productType: '',
  productModel: '',
  unitName: ''
})

// 统计数据
const statistics = reactive({
  inboundQuantity: 0,
  inboundAmount: '0.00',
  outboundQuantity: 0,
  outboundAmount: '0.00'
})

// 表单引用
const searchFormRef = ref()

// 新增弹窗表单数据
const addForm = reactive({
  productI_Id: parseInt(route.query.id), // 商品外键，从路由参数获取
  productName: '', // 商品名称
  inOutNo: '',
  inOutTiem: '',
  businessType: '',
  inOutType: '',
  inNumber: 0,
  outNumbber: 0,
  inMoney: 0,
  outMoney: 0,
  batch_Id: '' // 批次号
})

// 新增弹窗表单验证规则
const addFormRules = reactive({
  inOutNo: [{ required: true, message: '请输入出入库单号', trigger: 'blur' }],
  inOutTiem: [{ required: true, message: '请选择出入库日期', trigger: 'change' }],
  businessType: [{ required: true, message: '请选择业务类型', trigger: 'change' }],
  inOutType: [{ required: true, message: '请选择出入库类型', trigger: 'change' }]
})



// 从出入库流水数据中提取商品信息
const extractProductInfo = (data) => {
  console.log('提取商品信息 - 原始数据:', data)
  
  if (data && data.length > 0) {
    // 从第一条记录中提取商品信息（因为都是同一个商品）
    const firstRecord = data[0]
    console.log('第一条记录:', firstRecord)
    
    // 从联表查询返回的数据中提取商品信息
    productInfo.productName = firstRecord.productName || ''
    productInfo.productNo = firstRecord.productNo || ''
    productInfo.productType = firstRecord.productTypeId || ''
    productInfo.productModel = firstRecord.productModel || ''
    productInfo.unitName = firstRecord.unitName || ''
    productInfo.batch = firstRecord.batch_Id || '' // 提取批次信息
    
    console.log('从流水数据提取商品信息:', productInfo)
  } else {
    console.log('没有数据，无法提取商品信息')
  }
}

// 查询数据
const loadData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      ...searchForm,
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const res = await TZRead.get("/api/Product/inout-list", { params })
    
    if (res.data.code === 200) {
      // 处理数据：将0值转换为空，格式化日期
      const processedData = res.data.pageData.map((item, index) => {
        const processedItem = {
          ...item,
          index: (pagination.pageIndex - 1) * pagination.pageSize + index + 1,
          // 将0值转换为空
          inNumber: item.inNumber === 0 ? '' : item.inNumber,
          outNumbber: item.outNumbber === 0 ? '' : item.outNumbber,
          inMoney: item.inMoney === 0 ? '' : item.inMoney,
          outMoney: item.outMoney === 0 ? '' : item.outMoney,
          // 格式化制单日期
          createTime: item.createTime ? moment(item.createTime).format('YYYY-MM-DD') : ''
        }
        
        console.log('处理前:', item)
        console.log('处理后:', processedItem)
        
        return processedItem
      })
      
      tableData.value = processedData
      pagination.total = res.data.totalCount
      
      // 从流水数据中提取商品信息
      extractProductInfo(res.data.pageData)
      
      // 更新统计数据
      updateStatistics(res.data.pageData)
      
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(res.data.message || '查询失败')
    }
  } catch (error) {
    ElMessage.error('查询失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 更新统计数据
const updateStatistics = (data) => {
  let inboundQty = 0
  let inboundAmt = 0
  let outboundQty = 0
  let outboundAmt = 0
  
  data.forEach(item => {
    // 使用原始数据进行统计计算（未处理0值）
    inboundQty += item.inNumber || 0
    inboundAmt += item.inMoney || 0
    outboundQty += item.outNumbber || 0
    outboundAmt += item.outMoney || 0
  })
  
  statistics.inboundQuantity = inboundQty
  statistics.inboundAmount = inboundAmt.toFixed(2)
  statistics.outboundQuantity = outboundQty
  statistics.outboundAmount = outboundAmt.toFixed(2)
}

// 查询按钮
const handleSearch = () => {
  pagination.pageIndex = 1
  loadData()
}

// 重置按钮
const handleReset = () => {
  // 保存商品ID
  const productId = searchForm.productId
  
  // 重置表单
  searchFormRef.value?.resetFields()
  
  // 恢复商品ID
  searchForm.productId = productId
  
  pagination.pageIndex = 1
  loadData()
}

// 刷新按钮
const handleRefresh = () => {
  loadData()
}

// 导出按钮
const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  loadData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.pageIndex = page
  loadData()
}

// 入库数量变化处理
const handleInNumberChange = (value) => {
  // 暂时移除所有逻辑，让输入框正常工作
}

// 出库数量变化处理
const handleOutNumberChange = (value) => {
  // 暂时移除所有逻辑，让输入框正常工作
}

// 入库金额变化处理
const handleInMoneyChange = (value) => {
  // 暂时移除所有逻辑，让输入框正常工作
}

// 出库金额变化处理
const handleOutMoneyChange = (value) => {
  // 暂时移除所有逻辑，让输入框正常工作
}

// 关闭弹窗处理

const handleDialogClose = () => {
  addFormRef.value?.resetFields()
  addLoading.value = false
}

// 新增弹窗确定按钮
const handleAddSubmit = () => {
  addFormRef.value?.validate(async (valid) => {
    if (valid) {
      addLoading.value = true
      try {
        const res = await TZWrite.post("/api/ProductAddInout", addForm)
        if (res.data.code === 200) {
          ElMessage.success('新增成功')
          dialogVisible.value = false
          loadData() // 刷新列表
        } else {
          ElMessage.error(res.data.message || '新增失败')
        }
      } catch (error) {
        ElMessage.error('新增失败：' + error.message)
      } finally {
        addLoading.value = false
      }
    }
  })
}

// 新增弹窗相关变量
const dialogVisible = ref(false)
const addLoading = ref(false)
const addFormRef = ref()

// 生成出入库单号
const generateInOutNo = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  
  return `IO${year}${month}${day}${hours}${minutes}${seconds}${random}`
}

// 新增按钮点击事件
const AddRow = () => {
  // 重置表单
  addForm.productI_Id = parseInt(route.query.id)
  addForm.productName = productInfo.productName + ' ' + productInfo.productNo // 设置商品名称
  addForm.inOutNo = generateInOutNo() // 自动生成单号
  addForm.inOutTiem = moment().format('YYYY-MM-DD') // 默认今天
  addForm.businessType = ''
  addForm.inOutType = ''
  addForm.inNumber = 0
  addForm.outNumbber = 0
  addForm.inMoney = 0
  addForm.outMoney = 0
  addForm.batch_Id = productInfo.batch || '' // 设置批次信息
  
  // 打开弹窗
  dialogVisible.value = true
}

// 页面加载时执行
onMounted(async () => {
  console.log('路由参数:', route.query)
  console.log('商品ID:', searchForm.productId)
  
  // 直接加载出入库流水数据，商品信息会从流水数据中提取
  await loadData()
})


</script>

<style scoped>
.inout-flow-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.product-info-section {
  margin-bottom: 20px;
}

.product-info-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.product-details {
  display: flex;
  gap: 30px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: 500;
  color: #666;
  margin-right: 5px;
}





.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.statistics-section {
  margin-bottom: 20px;
}

.statistics-cards {
  display: flex;
  gap: 20px;
}

.stat-card {
  flex: 1;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.stat-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-label {
  color: #666;
}

.stat-value {
  font-weight: bold;
  font-size: 18px;
}

.inbound-value {
  color: #409eff;
}

.outbound-value {
  color: #e6a23c;
}

.table-actions {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

.pagination-section {
  display: flex;
  justify-content: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 新增弹窗样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style> 